package com.sise.aio和bio和nio.aio.基于aio的聊天室;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author idea
 * @data 2019/1/22
 */
public class Server {


    public final static int PORT = 9000;

    private AsynchronousServerSocketChannel server;

    public Server() throws IOException {
        server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(InetAddress.getLocalHost(), PORT));
    }


    public void startWithFuture() throws ExecutionException, InterruptedException {
        while(true){
            Future<AsynchronousSocketChannel> future=server.accept();
            //确保是否获取到了链接
            AsynchronousSocketChannel socket=future.get();


        }
    }

    public void handleWithFuture(AsynchronousSocketChannel channel) throws InterruptedException, ExecutionException, TimeoutException {
        ByteBuffer readBUff=ByteBuffer.allocate(200);
        readBUff.clear();
        while(true) {
            Integer integer = channel.read(readBUff).get(10, TimeUnit.SECONDS);
            System.out.println("read:" + integer);
            if (integer == -1) {
                break;
            }
            readBUff.flip();
            System.out.println("recived:"+ Charset.forName("UTF-8"));
            readBUff.clear();
        }

    }

    public void handleWithCompletionHandler(final AsynchronousSocketChannel channel){
        final ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        channel.read(byteBuffer, 10, TimeUnit.SECONDS, null, new CompletionHandler<Integer, Object>() {

            @Override
            public void completed(Integer result, Object attachment) {
                System.out.println("读取的内容："+result);
                if(result==-1) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                byteBuffer.flip();
                System.out.println("message:"+Charset.forName("utf-8").decode(byteBuffer));
                byteBuffer.clear();
                channel.read(byteBuffer,10,TimeUnit.SECONDS,null,this);


            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
    }


    public void startWithCompletionHandler(){
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            @Override
            public void completed(AsynchronousSocketChannel result, Object attachment) {
                server.accept(null, this);// 再此接收客户端连接
                handleWithCompletionHandler(result);
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.out.println("服务器异常！");
            }
        });
    }

    public static void main(String args[]) throws Exception {
//        new AIOServer().startWithFuture();
        new Server().startWithCompletionHandler();
        Thread.sleep(100000);
    }


}
